package com.wisemoresystem.seal.action.bank;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

import org.ne.framework.data.util.ChkTools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.wisemoresystem.seal.action.location.LocationAction;
import com.wisemoresystem.seal.base.action.ProjBaseAction;
import com.wisemoresystem.seal.base.tip.Tip;
import com.wisemoresystem.seal.config.Config;
import com.wisemoresystem.seal.config.FileFolderTools;
import com.wisemoresystem.seal.model.t_bank_verify;
import com.wisemoresystem.seal.model.t_file;
import com.wisemoresystem.seal.model.t_bank;
import com.wisemoresystem.seal.model.t_location;
import com.wisemoresystem.seal.service.BankSealService;
import com.wisemoresystem.seal.service.BankService;
import com.wisemoresystem.seal.service.LocationService;
import com.wisemoresystem.seal.util.ExcelReadToolForList;
import com.wisemoresystem.seal.util.doc.excel.ExcelExport;
import com.wisemoresystem.seal.util.doc.excel.ExcelReadTools;
import com.wisemoresystem.seal.util.json.JsonTools;
import com.wisemoresystem.seal.web.WebTools;

/**
 * 机构
 * 
 * @author Administrator
 *
 */
@Controller("ixBank")
@Scope("prototype")
@RequestMapping("/ix/bank")
public class BankAction extends ProjBaseAction {

	@Autowired
	private BankService bService;
	@Autowired
	private BankSealService sbService;
	@Autowired
	private LocationService lService;

	/**
	 * 转发所有的机构信息,在页面形成树形结构.
	 * 
	 * @param bank_id
	 *            选择的机构的id
	 * @return
	 */
	@RequestMapping("/tree")
	public ModelAndView tree(String bank_id) {

		List<Map<String, Object>> list = bService.selectUserBank();
		String bankJson = JsonTools.toJson(list);

		ModelAndView mv = new ModelAndView("/jsp/bank/tree");
		mv.addObject("bankJson", bankJson);
		mv.addObject("bank_id", bank_id);
		return mv;
	}

	/**
	 * 转发所有的区域信息.
	 * 
	 * @return
	 */
	@RequestMapping("/get_location")
	public ModelAndView get_location() {

		// List<Map<String, Object>> list = lService.selectLocation();
		// String locationJson = JsonTools.toJson(list);
		if (LocationAction.list == null) {
			LocationAction.list = lService.selectLocation();
			LocationAction.locationJson = JsonTools.toJson(LocationAction.list);
		}

		ModelAndView mv = new ModelAndView("/jsp/bank/getlocation");
		mv.addObject("locationJson", LocationAction.locationJson);
		return mv;
	}

	/**
	 * 去向添加页面
	 * 
	 * @return
	 */
	@RequestMapping("/add_form")
	public ModelAndView add_form() {

		List<Map<String, Object>> list = bService.selectBankLevel();

		ModelAndView mv = new ModelAndView("/jsp/bank/add_form");
		if (ChkTools.isNotNull(list))
			mv.addObject("bankLevel", list.get(0));
		return mv;
	}

	/**
	 * 添加机构
	 * 
	 * @param bank
	 *            要修改的机构信息
	 * @return
	 */
	@RequestMapping("/add")
	public ModelAndView add(t_bank bank) {

		bank.setUser_id(WebTools.getCurrentUserId());
		if (ChkTools.isNull(bank.getSuper_id())) {
			bank.setSuper_id("root");
		}
		String after = JsonTools.toJson(bank);

		t_bank_verify verify = new t_bank_verify();
		verify.setSubmit_user_id(WebTools.getCurrentUserId());
		verify.setBefore_v(null);
		verify.setAfter_v(after);
		verify.setFlag_note("机构增加审核");
		verify.setFlag_type("机构审核");
		verify.setUser_id(WebTools.getCurrentUserId());
		verify.setBefore_bank_id(WebTools.getCurrentBankId());
		bService.saveObj(verify);
		logT.logH("新增机构待审核", t_bank_verify.class, verify.get_id());

		super.setTipMsg("保存成功！", Tip.Type.success);
		ModelAndView mv = new ModelAndView("redirect:tree.htm");
		mv.addObject("bank_id", bank.getSuper_id());
		return mv;
	}

	/**
	 * 转发要修改的机构信息
	 * 
	 * @param bank_id
	 *            机构id
	 * @return
	 */
	@RequestMapping("/edit_form")
	public ModelAndView edit_form(String bank_id) {
		int level = bService.getBankLevel(bank_id);
		List<Map<String, Object>> list = bService.selectBankLevel();
		String list2 = bService.selectUbank2(bank_id);

		t_bank tBank = bService.findObjById(bank_id, t_bank.class);
		t_bank superBank = bService.findObjById(tBank.getSuper_id(),
				t_bank.class);
		t_location location = bService.findObjById(tBank.getArea_id(),
				t_location.class);

		ModelAndView mv = new ModelAndView("/jsp/bank/edit_form");
		mv.addObject("bank", tBank);
		mv.addObject("superBank", superBank);
		mv.addObject("location", location);
		mv.addObject("list2", list2);
		if (ChkTools.isNotNull(list))
			mv.addObject("bankLevel", list.get(level - 1));
		if (ChkTools.isNotNull(location)) {
			t_location loc = lService.selectLocationByCode(location.getCode()
					.substring(0, 2) + "0000");
			mv.addObject("loc", loc);
		}
		return mv;
	}

	/**
	 * 修改机构
	 * 
	 * @param id
	 *            当前id
	 * @param bank
	 *            当前机构信息
	 * @param bank_id
	 *            修改之后的id
	 * @return
	 */
	@RequestMapping("/edit")
	public ModelAndView edit(String id, t_bank bank, String bank_id) {

		t_bank tBank = bService.findObjById(id, t_bank.class);

		if (!tBank.equals(bank)) {
			String before = JsonTools.toJson(tBank);

			tBank.setFlag("修改中");
			bService.updateObj(tBank);
			if (ChkTools.isNotNull(bank_id)) {
				bank.setSuper_id(bank_id);
				int lev = bService.getBankLevel(bank_id);
				List<Map<String, Object>> list = bService.selectBankLevel();
				bank.setLevel_id(list.get(lev).get("_id") + "");
			}
			String after = JsonTools.toJson(bank); // 修改之后的机构 字符串

			t_bank_verify verify = new t_bank_verify();
			verify.setSubmit_user_id(WebTools.getCurrentUserId());
			verify.setBefore_v(before);// 在检查表中 保存 修改之后的json字符串
			verify.setAfter_v(after); // 在检查表中 保存 之后的json
			verify.setFlag_note("机构修改审核");
			verify.setFlag_type("机构审核");
			verify.setBefore_bank_id(tBank.get_id());
			verify.setUser_id(WebTools.getCurrentBankId());
			bService.saveObj(verify);
			super.setTipMsg("修改操作成功！", Tip.Type.success);

			logT.logH("修改机构待审核", t_bank_verify.class, verify.get_id());

		} else {
			super.setTipMsg("请确定修改的内容！", Tip.Type.warning);
		}

		ModelAndView mv = new ModelAndView("redirect:tree.htm");
		mv.addObject("bank_id", id);
		return mv;
	}

	/**
	 * 删除机构
	 * 
	 * @param id
	 *            要删除的机构id
	 * @return
	 */
	@RequestMapping("/del")
	public ModelAndView edit(String id) {

		t_bank tBank = bService.findObjById(id, t_bank.class);
		String before = JsonTools.toJson(tBank);

		tBank.setFlag("撤销中");
		bService.updateObj(tBank);

		t_bank_verify verify = new t_bank_verify();
		verify.setSubmit_user_id(WebTools.getCurrentUserId());
		verify.setBefore_v(before);
		verify.setAfter_v(null);
		verify.setFlag_note("机构撤销审核");
		verify.setFlag_type("机构审核");
		verify.setBefore_bank_id(WebTools.getCurrentBankId());
		bService.saveObj(verify);
		logT.logH("撤销机构待审核", t_bank_verify.class, verify.get_id());

		super.setTipMsg("撤销操作成功！", Tip.Type.success);
		ModelAndView mv = new ModelAndView("redirect:tree.htm");
		mv.addObject("bank_id", id);
		return mv;
	}

	/**
	 * 为机构添加子机构
	 * 
	 * @param id
	 *            要添加子机构的id
	 * @return
	 */
	@RequestMapping("/add_child")
	public ModelAndView add_child(String id) {

		int level = bService.getBankLevel(id);

		if (level == 6) {
			super.setTipMsg("机构级别超过限制！", Tip.Type.warning);
			ModelAndView mv = new ModelAndView("redirect:edit_form.htm");
			mv.addObject("bank_id", id);
			return mv;
		}

		List<Map<String, Object>> list = bService.selectBankLevel();
		t_bank tBank = bService.findObjById(id, t_bank.class);

		ModelAndView mv = new ModelAndView("/jsp/bank/add_child");
		mv.addObject("bank", tBank);
		if (ChkTools.isNotNull(list))
			mv.addObject("bankLevel", list.get(level));
		return mv;
	}

	/**
	 * 获取机构列表
	 * 
	 * @return
	 */
	@RequestMapping("/get_bank")
	public ModelAndView get_bank() {

		List<Map<String, Object>> list = bService.selectBank();
		String bankJson = JsonTools.toJson(list);

		ModelAndView mv = new ModelAndView("/jsp/bank/get/getbank");
		mv.addObject("bankJson", bankJson);
		return mv;
	}

	/**
	 * 获取机构信息
	 * 
	 * @param bank_id
	 *            当前机构的id
	 * @return
	 */
	@RequestMapping("/get_level_bank")
	public ModelAndView get_level_bank(String bank_id) {

		List<Map<String, Object>> list = bService.selectLevelBank(bank_id);
		String bankJson = JsonTools.toJson(list);

		ModelAndView mv = new ModelAndView("/jsp/bank/get/getbank");
		mv.addObject("bankJson", bankJson);
		return mv;
	}

	/**
	 * 网点菜单
	 * 
	 * @param bank_id
	 * @return
	 */
	@RequestMapping("/get_same_bank")
	public ModelAndView get_same_bank(String bank_id) {

		List<Map<String, Object>> list = bService.selectNetBank(bank_id);
		String bankJson = JsonTools.toJson(list);

		ModelAndView mv = new ModelAndView("/jsp/bank/get/getbank");
		mv.addObject("bankJson", bankJson);
		return mv;
	}

	/**
	 * 当前机构的下级别菜单
	 * 
	 * @return
	 */
	@RequestMapping("/get_lowerbank")
	public ModelAndView get_lowerbank() {

		List<Map<String, Object>> list = bService.selectLowerBank();
		String bankJson = JsonTools.toJson(list);

		ModelAndView mv = new ModelAndView("/jsp/bank/get/getbank");
		mv.addObject("bankJson", bankJson);
		return mv;
	}

	/**
	 * 获取当前机构和下属机构菜单
	 * 
	 * @return
	 */
	@RequestMapping("/get_userbank")
	public ModelAndView get_userbank() {

		List<Map<String, Object>> list = bService.selectUserBank();
		String bankJson = JsonTools.toJson(list);

		ModelAndView mv = new ModelAndView("/jsp/bank/get/getbank");
		mv.addObject("bankJson", bankJson);
		return mv;
	}

	// 模板
	/**
	 * 区域模板
	 * 
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/export_m")
	public ModelAndView exportMo() throws IOException {
		String tit = "中国区域及其编码";

		String[] arrays = { "区域编码", "地区名称", "所属区域编码" };

		ExcelExport<t_bank> ts = new ExcelExport<t_bank>();
		String filename = System.currentTimeMillis() + ".xls";

		File file = new File(FileFolderTools.getExportFolder(), filename);
		if (!file.getParentFile().exists()) {
			file.mkdirs();
		}
		OutputStream os = null;
		try {
			os = new FileOutputStream(file);
			ts.exportExcelL(tit, "中国区域及其编码", arrays, os);
			os.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (os != null) {
				os.close();
			}
		}
		ModelAndView mv = new ModelAndView("redirect:"
				+ FileFolderTools.getExportUrl() + filename);
		return mv;
	}

	// //工资表
	// @RequestMapping("/export_c")
	// public ModelAndView export(String enterprise_id, String month) throws
	// IOException {
	// String tit = "中国区域及其编码";
	//
	// String[] arrays = {"用工号","账号", "身份证号", "姓名", "应发工资", "养老保险扣款","失业保险扣款",
	// "医疗保险扣款", "大病扣款", "公积金扣款", "其他扣款", "个调税", "扣款合计", "实发工资"};
	//
	// List<Map<String, Object>> list = bService.downloadMonthSalaryList();
	//
	// ExcelExport<t_bank> ts = new ExcelExport<t_bank>();
	//
	// String filename = System.currentTimeMillis() + ".xls";
	// File file = new File(FileFolderTools.getExportFolder(), filename);
	// if (!file.getParentFile().exists()) {
	// file.mkdirs();
	// }
	// OutputStream os = null;
	// try {
	// os = new FileOutputStream(file);
	// ts.exportExcel(tit,"工资表单", arrays, list, os);
	// os.flush();
	// } catch (IOException e) {
	// e.printStackTrace();
	// } finally {
	// if (os != null) {
	// os.close();
	// }
	// }
	// ModelAndView mv = new ModelAndView("redirect:"
	// + FileFolderTools.getExportUrl() + filename);
	// return mv;
	// }
	/**
	 * 区域导入
	 * 
	 * @param file_id
	 *            文件id
	 * @throws IOException
	 */
	@RequestMapping("/import_c")
	public void importlinkmans(String file_id) throws IOException {
		resp.setCharacterEncoding("utf-8");

		t_file tf = bService.findObjById(file_id, t_file.class);
		File file = new File(
				Config.DATA_PATH + File.separator + tf.getFolder(),
				tf.getNew_file_name());
		if (!file.exists()) {
			file = new File(Config.DATA_PATH, "file404.jpg");
		}

		InputStream is = null;
		try {
			is = new FileInputStream(file);
			// 对读取Excel表格标题测试
			ExcelReadTools excelReader = new ExcelReadTools();

			// 对读取Excel表格内容测试
			Map<Integer, String> map = excelReader.readExcelContent(is);
			String par = map.get(1);
			String[] obj = par.split("#");
			String[] content = { "code", "name", "super_code" };
			try {
				List<Map<String, Object>> list = ExcelReadToolForList
						.turnToList(content, map, obj.length);
				try {
					bService.saveBank(list);
				} catch (RuntimeException e1) {
					resp.getWriter().print("导入失败！");
					resp.getWriter().flush();
					return;
				}
			} catch (RuntimeException e) {
				resp.getWriter().print("导入文件不符合！");
				resp.getWriter().flush();
				return;
			}

			resp.getWriter().print("导入成功");
			resp.getWriter().flush();
		} catch (FileNotFoundException e) {
			// System.out.println("未找到指定路径的文件!");
			e.printStackTrace();
		} finally {
			try {
				if (is != null) {
					is.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 区域编码唯一
	 * 
	 * @param bank_id
	 *            机构id
	 * @param code
	 *            区域编码
	 * @throws IOException
	 */
	@RequestMapping("/unique_code")
	public void unique_code(String bank_id, String code) throws IOException {

		boolean islive = bService.checkUniqueCode(bank_id, code);

		resp.getWriter().print(islive);
		resp.getWriter().flush();
	}
}
